import React, { Component } from 'react';
// width 开关宽度  默认52px 
// height 开关高度 默认32px 圆球高、宽度和这个一直
// background 开关关闭的背景颜色 默认'rgba(228,228,228,1)'
// activebackground 激活的背景颜色 默认 '#00ff00'
// transition 过度方式  默认'all 0.5s ease'
// checked 设置开关是否打开  默认关闭
// circleColor 秋的颜色
// this.props.myClick(参数1) 父组件传递过来的函数，可以传递参数给父组件
class Com extends Component {
	constructor(props){
		super(props)
		this.ref = React.createRef()
		this.state= {
			width: this.props.width || '52px',//开关宽度
			height: this.props.height ||'32px',//开关高度
			background: this.props.background || 'rgba(228,228,228,1)',// 未选中的颜色
			borderRadius: this.props.height|| '16px',// 设置为高度的一般，确保圆角
			display: 'block',// 设置元素类型，确保能够设置宽高
			left: '0',
			checked: this.props.checked || false,
			transition: this.props.transition || 'all 0.5s ease'
		}
	}
	changeChecked(){
		this.setState({checked: !this.state.checked},()=>{this.checkInput()})
	}
	componentDidMount(){
		// console.log(this.ref)
		// console.log(this.props)
		// console.log(this.ref.current.checked)
		if(this.state.checked){
			this.checkInput()
		}
	}
	checkInput(){
		// 判断单位 
		// console.log(this.props.width)
		// console.log(1,this.state.width)
		const unit = this.state.width.replace(/[0-9.]+/ig, '')
		// console.log(unit)
		// console.log(unit)
		//设置背景颜色
		const bg = this.ref.current.checked ? this.props.activebackground ||('#008c8c') : this.props.background || 'rgba(228,228,228,1)'
		//设置开关位置
		const left = this.ref.current.checked ? ((parseFloat(this.state.width) - parseFloat(this.state.height))+unit):0
		// console.log(left,(parseFloat(this.state.width) - parseFloat(this.state.height)))
		this.setState({
			background: bg,
			left: left
		})
		// console.log(this.ref.current.checked)
		if(this.props.myClick){
			this.props.myClick(this.ref.current.checked)
		}
	}
	render(){
		return (
			<div className='switch' style={{display:'inline-block', position: 'relative'}}>
				<label
					className='myswitch'
					style={this.state}
					// htmlFor="switch"
					onClick={()=>{
						// this.checkInput()
						// console.log(1)
						// this.setState({checked: !this.state.checked},()=>{this.checkInput()})
					}}
				>
				<input
					ref= {this.ref}
					style={{display: 'none'}}
					// id='switch'
					type="checkbox" className="switch"
					checked={this.state.checked}
					onChange= {()=>{
						this.changeChecked()
					}}
				/>
				</label>
				<div className="circle" 
					style={{
						height: this.state.height, 
						width: this.state.height,
						position: "absolute",
						left: this.state.left,
						top: 0,
						backgroundColor: this.props.circleColor || '#00ff00',
						borderRadius: '50%',
						transition: this.state.transition
						}}
						onClick={()=>{
							this.setState({checked: !this.state.checked},()=>{this.checkInput()})
						}}
					>
				</div>
			</div>
		)
	}
}
export default Com